#pragma once

#include"util.hpp"
#include"data.hpp"
#include"config.hpp"
#include<unistd.h>
//#include"ctime"
extern cloud::DataManager* data;

namespace cloud{

    class HotManager{
        private:
        std::string _back_dir;
        std::string _pack_dir;
        std::string _pack_suffix;
        int _hot_time;
        bool HotJudge(const std::string& filename)
        {
            Util::FileUtil file(filename);
            time_t cut_time = time(nullptr);
            time_t last_atime = file.LastAccTime();
            if(cut_time - last_atime > _hot_time)
            {
                return true;//热点文件
            }
            return false;//非热点文件
        }
        public:
        HotManager()
        {
            Config* conf = Config::GetInstance();
            _back_dir = conf->GetBackDir();
            _pack_dir = conf->GetPackDir();
            Util::FileUtil back_dir(_back_dir);
            Util::FileUtil pack_dir(_pack_dir);

            if(back_dir.Exists() == false)
            {
                back_dir.CreateDirectory();
            }
            if(pack_dir.Exists() == false)
            {
                pack_dir.CreateDirectory();
            }
            _pack_suffix = conf->GetPackDileSuffix();
            _hot_time = conf->GetHotTime();

        }

        bool RunModule()
        {
            while(true)
            {
                Util::FileUtil back_dir(_back_dir);
                std::vector<std::string> afile;
                back_dir.ScanDirectory(&afile);
                for(int i = 0 ;i < afile.size();i++)
                {
                    std::string file = afile[i];
                    //std::cout << file<<std::endl;
                    if(HotJudge(file) == false)
                    {
                        continue;
                    }
                    BackupInfo bi;
                    if(data->GetOneByRealPath(file,&bi) == false)
                    {
                        bi.NewBackupInfo(file);
                    }
                    Util::FileUtil cfile(file);
                    cfile.Compress(bi.pack_path);
                    cfile.Remove();
                    bi.pack_flag = true;
                    data->Update(bi);
                }
                usleep(10000);             
            }
            return true;

        }

    };

}
